package com.crazybytex.fragment.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description server
 * @Author 本文作者 程序员潇然 疯狂的字节X https://www.crazybytex.com/
 * @Date 11:59 2022/7/4
 **/
public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        Reader reader = null;
        OutputStream os = null;
        PrintWriter pw = null;
        try {
            //1、创建一个服务器端Socket，即ServerSocket，指定绑定的端口，并监听此端口
            //1024-65535的某个端口
            serverSocket = new ServerSocket(9527);
            //2、调用accept()方法开始监听，等待客户端的连接
            socket = serverSocket.accept();
            //3、获取输入流，并读取客户端信息
            reader = new InputStreamReader(socket.getInputStream());
            char chars[] = new char[1024];
            int len;
            String strClient = "";
            while ((len = reader.read(chars)) != -1) {
                strClient = new String(chars, 0, len);
                System.out.println("Receive from client message=: " + strClient);
            }
            //关闭输入流
            socket.shutdownInput();
            //4、获取输出流，响应客户端的请求
            os = socket.getOutputStream();
            pw = new PrintWriter(os);
            pw.write("Hello client ,response from server");
            pw.flush();
            //5、关闭资源
            pw.close();
            os.close();
            reader.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
